package com.hzw.saas.common.util.enums;

import java.util.Objects;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;

/**
 * 存储空间
 *
 * @author zzl
 * @since 02/26/2021
 */
public enum StorageUnitEnum {

    BYTE(unitBaseValue(0), "B"),
    KILOBYTE(unitBaseValue(1), "K"),
    MEGABYTE(unitBaseValue(2), "M"),
    GIGABYTE(unitBaseValue(3), "G"),
    TERABYTE(unitBaseValue(4), "T"),
    PETABYTE(unitBaseValue(5), "P"),
    EXABYTE(unitBaseValue(6), "E"),
    ;

    private static final long UNIT_SCALE = 1024L;

    /**
     * 单位时间相对于秒的换算值
     */
    private final Long value;
    private final String text;

    StorageUnitEnum(Long value, String text) {
        this.value = value;
        this.text = text;
    }

    public Long value() {
        return value;
    }

    public String text() {
        return text;
    }

    public static StorageUnitEnum instance(String text) {
        for (StorageUnitEnum value : StorageUnitEnum.values()) {
            if (Objects.equals(value.text, text))
                return value;
        }
        return null;
    }

    public static StorageUnitEnum assertInstance(String text) {
        StorageUnitEnum instance = instance(text);
        Assert.notNull(instance, "存储单位异常: {}", text);
        return instance;
    }

    private static long unitBaseValue(int index) {
        return NumberUtil.pow(UNIT_SCALE, index).longValue();
    }

}
